package jsp;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author:石小俊
 * @Date:2022/12/14 13:33
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if("/show.code".equals(path)){
            showCode(request,response);
        }
        if("/login.code".equals(path)){
            login(request,response);
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 验证码
        // 获取用户输入的验证码
        String code = request.getParameter("code");
        // 获取验证码图片的内容
        String image = (String) request.getSession().getAttribute("code");
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
            return;
        }
        // JDBC

    }

    public void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 1.在内存中定义一个画板
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
        // 2.获取画板中对应的画笔
        Graphics graphics = image.getGraphics();
        // 3.设置画笔所填充的内容区域
        graphics.fillRect(0,0,50,25);
        // 设置颜色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
        // 设置字体
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));
        // 生成验证码图片中的内容
        // 随机生成4位英文字母或者数字
        String s = "1234567890qwertyuioplkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();
        System.out.println("验证码:"+code);
        // 将生成的图片的内容存储到session,便于校验
        request.getSession().setAttribute("code",code);
        // 将验证码内容绘制到图片中
        graphics.drawString(code,5,18);
        // 生成对应的图片
        // 在Java开发中,通过代码生成的图片一般使用JPEG格式的
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

}
